import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({
  showSpinner: false // 关闭右上角的圈圈
})

// vue-router3.x
/* import VueRouter from 'vue-router'
Vue.use(VueRouter)
new VueRouter({ routes }) */

// Vue3 和周边配套（Pinia、VueRouter...），更强调函数式编程

// console.log(import.meta.env.BASE_URL, 888) // patient
const router = createRouter({
  // 路由模式
  // createWebHistory() => H5 的 history 模式
  // createWebHashHistory() => Hash 模式的路由
  // 参数表示项目的根地址
  // import.meta.env.BASE_URL 会找 vite.config.ts 中 base 选项，默认是 /
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login/index.vue'),
      meta: {
        title: '登录'
      }
    },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/index.vue'),
          meta: {
            title: '首页'
          }
        },
        {
          path: '/article',
          component: () => import('@/views/Article/index.vue'),
          meta: {
            title: '健康百科'
          }
        },
        {
          path: '/notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: {
            title: '消息中心'
          }
        },
        {
          path: '/user',
          component: () => import('@/views/User/index.vue'),
          meta: {
            title: '我的'
          }
        }
      ]
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: { title: '家庭档案' }
    },
    {
      path: '/consult/fast',
      component: () => import('@/views/Consult/ConsultFast.vue'),
      meta: { title: '极速问诊' }
    },
    {
      path: '/consult/dep',
      component: () => import('@/views/Consult/ConsultDep.vue'),
      meta: { title: '选择科室' }
    },
    {
      path: '/consult/illness',
      component: () => import('@/views/Consult/ConsultIllness.vue'),
      meta: { title: '病情描述' }
    },
    {
      path: '/consult/pay',
      component: () => import('@/views/Consult/ConsultPay.vue'),
      meta: { title: '问诊支付' }
    },
    {
      path: '/room',
      component: () => import('@/views/Room/index.vue'),
      meta: { title: '问诊室' }
    }
  ]
})

const whiteList = ['/login', '/404']

// Vue Router4.x 更建议通过 return 跳转页面
router.beforeEach((to) => {
  NProgress.start()
  const userStore = useUserStore()
  if (!userStore.user?.token && !whiteList.includes(to.path)) return '/login'
})

router.afterEach((to) => {
  NProgress.done()
  document.title = `优医问诊-${to.meta.title}`
})

export default router

// const route = useRoute() // 当前路由信息组成的对象，可以获取参数，this.$route
// const router = useRouter() // 路由实例，用来跳转的，this.$router
